﻿using Microsoft.AspNet.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ldhWebApiWF
{
    public class ClientAccessPolicyConnection : PersistentConnection
    {
        public override Task ProcessRequest(Microsoft.AspNet.SignalR.Hosting.HostContext context)
        {
            string[] urlArray = context.Request.Url.ToString().Split('/');

            string path = urlArray[urlArray.Length - 1];

            if (path.Equals("clientaccesspolicy.xml", StringComparison.InvariantCultureIgnoreCase))
            {
                //Convert policy to byteArray
                var array = Encoding.UTF8.GetBytes(ClientAccessPolicy);
                var segment = new ArraySegment<byte>(array);

                //Write response
                context.Response.ContentType = "text/xml";
                context.Response.Write(segment);

                //Return empty task to escape from SignalR's default Connection/Transport checks.
                return EmptyTask;
            }

            return EmptyTask;
        }

        private static readonly Task EmptyTask = MakeTask<object>(null);

        public static Task<T> MakeTask<T>(T value)
        {
            var tcs = new TaskCompletionSource<T>();
            tcs.SetResult(value);
            return tcs.Task;
        }

        public static readonly string ClientAccessPolicy =
            "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
                    + "<access-policy>"
                       + "<cross-domain-access>"
                         + "<policy>"
                           + "<allow-from http-request-headers=\"*\">"
                                + "<domain uri=\"*\"/>"
                           + "</allow-from>"
                           + "<grant-to>"
                                + "<resource path=\"/\" include-subpaths=\"true\"/>"
                           + "</grant-to>"
                        + "</policy>"
                    + "</cross-domain-access>"
                  + "</access-policy>";
    }
}
